import React, { useState, useEffect, useRef } from 'react';
import { 
  Card, Form, Input, InputNumber, Select, 
  Switch, Button, Tag, Collapse, Table, 
  Statistic, Typography, Divider, Space, Row, Col,
  Modal, List, Popconfirm, message, Tooltip, DatePicker,
  Tabs, Descriptions, Badge, Calendar, Popover, Empty,
  Progress
} from 'antd';
import { 
  CloseOutlined, ReloadOutlined, LineChartOutlined, SearchOutlined,
  SaveOutlined, FolderOpenOutlined, DeleteOutlined, EditOutlined,
  ArrowDownOutlined, TeamOutlined
} from '@ant-design/icons';
import * as echarts from 'echarts';
import { fetchStockCodes, runBacktest, stockGroupApi, stockInfoApi, strategyCombinationApi } from '../../api';
import { backCycleOpts, sortTypeOpts, tradeTypeOpts } from '../../constants';
import './index.css';
import moment from 'moment';

const { Option } = Select;
const { Panel } = Collapse;
const { Title, Text } = Typography;
const { TabPane } = Tabs;

// 收益曲线图组件
const ReturnsChart = ({ cumulativeReturns }) => {
  const chartRef = useRef(null);
  
  useEffect(() => {
    // 确保DOM已加载
    if (chartRef.current && cumulativeReturns && cumulativeReturns.length > 0) {
      // 初始化图表
      const chartInstance = echarts.init(chartRef.current);
      
      // 准备数据
      const dates = cumulativeReturns.map(item => item.date);
      const values = cumulativeReturns.map(item => ((item.cumulative_return - 1) * 100).toFixed(2));
      
      // 计算Y轴范围
      const numValues = values.map(v => parseFloat(v));
      const maxValue = Math.max(...numValues);
      const minValue = Math.min(...numValues);
      const yAxisPadding = Math.max(Math.abs(maxValue), Math.abs(minValue)) * 0.1;
      
      // 图表配置
      const option = {
        tooltip: {
          trigger: 'axis',
          formatter: function(params) {
            const date = moment(params[0].axisValue).format('YYYY-MM-DD');
            const value = params[0].data;
            return `${date}<br/>策略收益: ${value}%`;
          }
        },
        legend: {
          data: ['策略收益', '基准线'],
          top: 10
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: dates,
          boundaryGap: false,
          axisLabel: {
            formatter: function(value) {
              return moment(value).format('YYYY-MM-DD');
            }
          }
        },
        yAxis: {
          type: 'value',
          min: Math.floor(minValue - yAxisPadding),
          max: Math.ceil(maxValue + yAxisPadding),
          axisLabel: {
            formatter: '{value}%'
          },
          splitLine: {
            lineStyle: {
              type: 'dashed'
            }
          }
        },
        series: [
          {
            name: '策略收益',
            type: 'line',
            data: numValues,
            smooth: true,
            lineStyle: {
              width: 3,
              color: '#5B8FF9'
            },
            symbol: 'circle',
            symbolSize: 6,
            itemStyle: {
              color: '#5B8FF9',
              borderColor: '#fff',
              borderWidth: 2
            }
          },
          {
            name: '基准线',
            type: 'line',
            data: Array(dates.length).fill(0),
            lineStyle: {
              width: 2,
              color: '#d9d9d9',
              type: 'dashed'
            },
            symbol: 'none'
          }
        ]
      };
      
      // 添加标记区域 - 负值区域标红
      if (minValue < 0) {
        option.series[0].markArea = {
          itemStyle: {
            color: 'rgba(255, 0, 0, 0.06)'
          },
          data: [
            [
              { yAxis: 0, xAxis: 0 },
              { yAxis: minValue - yAxisPadding, xAxis: dates.length - 1 }
            ]
          ]
        };
      }
      
      // 设置配置项并渲染图表
      chartInstance.setOption(option);
      
      // 响应窗口大小变化
      const resizeHandler = () => {
        chartInstance.resize();
      };
      window.addEventListener('resize', resizeHandler);
      
      // 组件卸载时清理
      return () => {
        window.removeEventListener('resize', resizeHandler);
        chartInstance.dispose();
      };
    }
  }, [cumulativeReturns]);
  
  return (
    <div className="returns-chart">
      <div ref={chartRef} style={{ width: '100%', height: '400px' }}></div>
    </div>
  );
};

const Strategy = () => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [results, setResults] = useState(null);
  const [availableCodes, setAvailableCodes] = useState({
    history: [],
    real: []
  });
  const [showStockSelector, setShowStockSelector] = useState(false);
  const [selectedCodes, setSelectedCodes] = useState([
    "000016.XSHG", "000852.XSHG", "399673.XSHE", "513100.XSHG", "518880.XSHG"
  ]);
  
  // 股票组合相关状态
  const [stockGroups, setStockGroups] = useState([]);
  const [showGroupModal, setShowGroupModal] = useState(false);
  const [groupModalMode, setGroupModalMode] = useState('save'); // 'save' or 'load'
  const [groupName, setGroupName] = useState('');
  const [editingGroupId, setEditingGroupId] = useState(null);
  const [groupsLoading, setGroupsLoading] = useState(false);
  const [stockNameMap, setStockNameMap] = useState({}); // 存储股票代码到名称的映射

  // 策略组合相关状态
  const [strategyCombinations, setStrategyCombinations] = useState([]);
  const [showCombinationModal, setShowCombinationModal] = useState(false);
  const [selectedCombination, setSelectedCombination] = useState(null);
  const [combinationName, setCombinationName] = useState('');
  const [combinationsLoading, setCombinationsLoading] = useState(false);
  const [createNewCombination, setCreateNewCombination] = useState(false);

  // 加载保存的股票组合
  useEffect(() => {
    fetchStockGroups();
    fetchStockInfo();
    fetchStrategyCombinations();
  }, []);

  // 获取所有股票组合
  const fetchStockGroups = async () => {
    setGroupsLoading(true);
    try {
      const data = await stockGroupApi.getAllStockGroups();
      setStockGroups(data || []);
    } catch (error) {
      console.error('获取股票组合失败:', error);
      message.error('获取股票组合失败');
    } finally {
      setGroupsLoading(false);
    }
  };

  // 获取股票信息，建立代码到名称的映射
  const fetchStockInfo = async () => {
    try {
      const data = await stockInfoApi.getAllStockInfo();
      const nameMap = {};
      if (Array.isArray(data)) {
        data.forEach(stock => {
          nameMap[stock.code] = stock.name;
        });
      }
      setStockNameMap(nameMap);
    } catch (error) {
      console.error('获取股票信息失败:', error);
    }
  };

  // 获取所有策略组合
  const fetchStrategyCombinations = async () => {
    setCombinationsLoading(true);
    try {
      const data = await strategyCombinationApi.getAllCombinations();
      setStrategyCombinations(data || []);
    } catch (error) {
      console.error('获取策略组合失败:', error);
      message.error('获取策略组合失败');
    } finally {
      setCombinationsLoading(false);
    }
  };

  // 根据股票代码生成默认组合名称
  const generateDefaultGroupName = (codes) => {
    const names = codes.map(code => stockNameMap[code] || code)
                      ; // 只取前三个股票名称
    
    let groupName = names.join('-');
    
    // 如果有更多股票，添加"等"
    // if (codes.length > 3) {
    //   groupName += `等${codes.length}只`;
    // }
    
    return groupName;
  };

  // 获取可用的股票代码
  useEffect(() => {
    const loadStockCodes = async () => {
      try {
        const data = await fetchStockCodes();
        setAvailableCodes(data);
      } catch (error) {
        console.error('Error fetching stock codes:', error);
      }
    };
    
    loadStockCodes();
    
    // 设置表单初始值
    form.setFieldsValue({
      ischeckhs300: false,
      hs300_limit: 30,
      doType: 1,
      backCycle: "day",
      codes: ["000016.XSHG", "000852.XSHG", "399673.XSHE", "513100.XSHG", "518880.XSHG"],
      increaseday_range: 21,
      highday_range: 25,
      lowday_range: 17,
      sortType: 1,
      tradeType: 1,
      startDate: null
    });
  }, [form]);

  const handleAddCode = (code) => {
    if (!selectedCodes.includes(code)) {
      const newCodes = [...selectedCodes, code];
      setSelectedCodes(newCodes);
      form.setFieldsValue({ codes: newCodes });
    }
  };

  const handleRemoveCode = (code) => {
    const newCodes = selectedCodes.filter(c => c !== code);
    setSelectedCodes(newCodes);
    form.setFieldsValue({ codes: newCodes });
  };

  const toggleStockSelector = () => {
    setShowStockSelector(!showStockSelector);
  };

  const handleSubmit = async (values) => {
    setLoading(true);
    try {
      if(values.startDate) {
        values.startDate = moment(values.startDate).format('YYYY-MM-DD HH:mm:ss');
      } else {
        values.startDate = null;
      }
      const data = await runBacktest(values);
      setResults(data);
    } catch (error) {
      console.error('Error running backtest:', error);
    } finally {
      setLoading(false);
    }
  };

  // 打开保存组合模态框
  const openSaveGroupModal = () => {
    setGroupModalMode('save');
    // 生成默认组合名称
    const defaultName = generateDefaultGroupName(selectedCodes);
    setGroupName(defaultName);
    setEditingGroupId(null);
    setShowGroupModal(true);
  };

  // 打开加载组合模态框
  const openLoadGroupModal = () => {
    setGroupModalMode('load');
    fetchStockGroups(); // 刷新组合列表
    setShowGroupModal(true);
  };

  // 保存当前股票组合
  const saveCurrentGroup = async () => {
    if (!groupName.trim()) {
      message.error('请输入组合名称');
      return;
    }

    if (selectedCodes.length === 0) {
      message.error('请至少选择一个股票代码');
      return;
    }

    const groupData = {
      name: groupName,
      codes: [...selectedCodes]
    };

    try {
      if (editingGroupId !== null) {
        // 更新现有组合
        await stockGroupApi.updateStockGroup(editingGroupId, groupData);
        message.success(`已更新组合: ${groupName}`);
      } else {
        // 添加新组合
        await stockGroupApi.addStockGroup(groupData);
        message.success(`已保存组合: ${groupName}`);
      }
      
      fetchStockGroups();
      setShowGroupModal(false);
    } catch (error) {
      console.error('保存股票组合失败:', error);
      message.error('保存股票组合失败');
    }
  };

  // 加载股票组合
  const loadGroup = (group) => {
    setSelectedCodes(group.codes);
    form.setFieldsValue({ codes: group.codes });
    setShowGroupModal(false);
    message.success(`已加载组合: ${group.name}`);
  };

  // 编辑股票组合
  const editGroup = (group, id) => {
    setGroupModalMode('save');
    setGroupName(group.name);
    setEditingGroupId(id);
    setSelectedCodes(group.codes);
    form.setFieldsValue({ codes: group.codes });
    setShowGroupModal(true);
  };

  // 删除股票组合
  const deleteGroup = async (id) => {
    try {
      const response = await stockGroupApi.deleteStockGroup(id);
      message.success(response.message || '已删除组合');
      fetchStockGroups();
    } catch (error) {
      console.error('删除股票组合失败:', error);
      message.error('删除股票组合失败');
    }
  };

  // 表格列定义
  const columns = [
    {
      title: '日期',
      dataIndex: 'date',
      key: 'date',
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
      render: (text) => (
        <Tag color={text === 'buy' ? 'success' : 'error'}>
          {text === 'buy' ? '买入' : '卖出'}
        </Tag>
      ),
    },
    {
      title: '代码',
      dataIndex: 'code',
      key: 'code',
    },
    {
      title: '价格',
      dataIndex: 'price',
      key: 'price',
    },
    {
      title: '描述',
      dataIndex: 'desc',
      key: 'desc',
      render: (text) => text || '-',
    },
  ];

  // 渲染股票代码和名称
  const renderStockCodeWithName = (code) => {
    const name = stockNameMap[code];
    if (name) {
      return `${code} (${name})`;
    }
    return code;
  };

  // 格式化回撤数据显示
  const formatDrawdownPercent = (value) => {
    return `${(value * 100).toFixed(2)}%`;
  };

  // 获取月度收益率的颜色
  const getMonthReturnColor = (value) => {
    if (value > 0) return '#f50';
    if (value < 0) return '#2db7f5';
    return '#d9d9d9';
  };

  // 渲染月度日历单元格
  const renderMonthCalendarCell = (monthData) => {
    if (!monthData) return null;
    
    const returnValue = monthData.return;
    const color = getMonthReturnColor(returnValue);
    const formattedReturn = `${(returnValue * 100).toFixed(2)}%`;
    
    return (
      <div className="month-cell" style={{ color }}>
        <div className="month-return">{formattedReturn}</div>
      </div>
    );
  };

  // 渲染月度收益热图
  const renderMonthlyReturnsHeatmap = (monthlyReturns) => {
    if (!monthlyReturns || monthlyReturns.length === 0) return null;
    
    // 按年份分组
    const returnsByYear = {};
    monthlyReturns.forEach(item => {
      if (!returnsByYear[item.year]) {
        returnsByYear[item.year] = {};
      }
      returnsByYear[item.year][item.month] = item;
    });
    
    return (
      <div className="monthly-returns-heatmap">
        {Object.keys(returnsByYear).sort().map(year => (
          <Card 
            title={`${year}年月度收益`}
            size="small"
            className="year-card"
            key={year}
          >
            <div className="months-grid">
              {Array.from({ length: 12 }, (_, i) => i + 1).map(month => {
                const monthData = returnsByYear[year][month];
                if (!monthData) return (
                  <div key={month} className="month-cell empty">
                    {month}月
                  </div>
                );
                
                const returnValue = monthData.return;
                const color = getMonthReturnColor(returnValue);
                const formattedReturn = `${(returnValue * 100).toFixed(2)}%`;
                
                return (
                  <div 
                    key={month} 
                    className="month-cell" 
                    style={{ 
                      backgroundColor: color,
                      color: returnValue > 0 ? 'white' : 'black',
                      opacity: Math.min(0.8, Math.abs(returnValue) * 5 + 0.2)
                    }}
                  >
                    <div className="month-name">{month}月</div>
                    <div className="month-return">{formattedReturn}</div>
                  </div>
                );
              })}
            </div>
          </Card>
        ))}
      </div>
    );
  };

  // 渲染年度收益表格
  const renderYearlyReturnsTable = (yearlyReturns) => {
    if (!yearlyReturns || yearlyReturns.length === 0) return null;
    
    // 找到最大和最小收益率，用于计算进度条比例
    const maxReturn = Math.max(...yearlyReturns.map(item => Math.max(
      Math.abs(item.return), 
      Math.abs(item.compound_monthly_return || 0)
    )));
    
    return (
      <div className="yearly-returns-table">
        <Table
          dataSource={yearlyReturns.map((item, index) => ({
            key: index,
            year: item.year,
            return: item.return,
            return_percent: `${(item.return * 100).toFixed(2)}%`,
            compound_monthly_return: item.compound_monthly_return,
            compound_monthly_return_percent: `${(item.compound_monthly_return * 100).toFixed(2)}%`,
            months_count: item.months_count
          }))}
          columns={[
            {
              title: '年份',
              dataIndex: 'year',
              key: 'year',
              width: '10%'
            },
            {
              title: '直接计算收益率',
              dataIndex: 'return_percent',
              key: 'return',
              render: (text, record) => (
                <span style={{ 
                  color: record.return > 0 ? '#f50' : (record.return < 0 ? '#2db7f5' : '#000'),
                  fontWeight: 'bold'
                }}>
                  {text}
                </span>
              ),
              width: '15%'
            },
            {
              title: '月度累乘收益率',
              dataIndex: 'compound_monthly_return_percent',
              key: 'compound_monthly_return',
              render: (text, record) => (
                <span style={{ 
                  color: record.compound_monthly_return > 0 ? '#f50' : (record.compound_monthly_return < 0 ? '#2db7f5' : '#000'),
                  fontWeight: 'bold'
                }}>
                  {text}
                </span>
              ),
              width: '15%'
            },
            {
              title: '月数',
              dataIndex: 'months_count',
              key: 'months_count',
              width: '10%'
            },
            {
              title: '可视化',
              dataIndex: 'return',
              key: 'visualization',
              render: (value, record) => {
                const isPositive = value > 0;
                const percent = Math.min(Math.abs(value) / maxReturn * 100, 100);
                
                // 计算月度累乘收益率的百分比
                const compoundIsPositive = record.compound_monthly_return > 0;
                const compoundPercent = Math.min(Math.abs(record.compound_monthly_return) / maxReturn * 100, 100);
                
                return (
                  <div className="return-progress-container">
                    <div className="return-axis">
                      <div className="axis-line"></div>
                    </div>
                    {/* 直接计算收益率的条形图 */}
                    <div className={`return-bar ${isPositive ? 'positive' : 'negative'}`} 
                      style={{ 
                        width: `${percent/2}%`,
                        [isPositive ? 'left' : 'right']: '50%',
                        top: '3px',
                        height: '8px'
                      }}>
                    </div>
                    {/* 月度累乘收益率的条形图 */}
                    <div className={`return-bar ${compoundIsPositive ? 'positive-compound' : 'negative-compound'}`} 
                      style={{ 
                        width: `${compoundPercent / 2}%`,
                        [compoundIsPositive ? 'left' : 'right']: '50%',
                        top: '15px',
                        height: '8px'
                      }}>
                    </div>
                  </div>
                );
              },
              width: '50%'
            }
          ]}
          pagination={false}
          size="middle"
          bordered
        />
        <div className="legend" style={{ marginTop: '10px', display: 'flex', justifyContent: 'center', gap: '20px' }}>
          <div style={{ display: 'flex', alignItems: 'center' }}>
            <div style={{ width: '20px', height: '8px', backgroundColor: '#f50', marginRight: '5px' }}></div>
            <span>直接计算收益率（正）</span>
          </div>
          <div style={{ display: 'flex', alignItems: 'center' }}>
            <div style={{ width: '20px', height: '8px', backgroundColor: '#2db7f5', marginRight: '5px' }}></div>
            <span>直接计算收益率（负）</span>
          </div>
          <div style={{ display: 'flex', alignItems: 'center' }}>
            <div style={{ width: '20px', height: '8px', backgroundColor: '#fa8c16', marginRight: '5px' }}></div>
            <span>月度累乘收益率（正）</span>
          </div>
          <div style={{ display: 'flex', alignItems: 'center' }}>
            <div style={{ width: '20px', height: '8px', backgroundColor: '#13c2c2', marginRight: '5px' }}></div>
            <span>月度累乘收益率（负）</span>
          </div>
        </div>
        <div className="explanation" style={{ marginTop: '10px', padding: '10px', backgroundColor: '#f9f9f9', borderRadius: '4px' }}>
          <p><strong>说明：</strong></p>
          <p>1. <strong>直接计算收益率</strong>：使用年初第一个数据点和年末最后一个数据点计算的收益率</p>
          <p>2. <strong>月度累乘收益率</strong>：将每个月的收益率通过 (1+r₁)×(1+r₂)×...×(1+rₙ)-1 累乘计算得到</p>
          <p>两者之间的差异可能来自于数据点的选择、计算精度或者月度间的复利效应。</p>
        </div>
      </div>
    );
  };

  // 渲染收益曲线图
  const renderReturnsChart = (cumulativeReturns) => {
    if (!cumulativeReturns || cumulativeReturns.length === 0) return null;
    return <ReturnsChart cumulativeReturns={cumulativeReturns} />;
  };

  // 计算统计指标
  const calculateStatistics = (cumulativeReturns) => {
    if (!cumulativeReturns || cumulativeReturns.length < 2) {
      return {
        finalReturn: 0,
        annualizedReturn: 0,
        maxDrawdown: 0,
        volatility: 0,
        sharpeRatio: 0,
        winRate: 0
      };
    }
    
    // 最终收益率
    const firstValue = cumulativeReturns[0].cumulative_return;
    const lastValue = cumulativeReturns[cumulativeReturns.length - 1].cumulative_return;
    const finalReturn = (lastValue / firstValue) - 1;
    
    // 计算年化收益率
    const firstDate = moment(cumulativeReturns[0].date);
    const lastDate = moment(cumulativeReturns[cumulativeReturns.length - 1].date);
    const years = lastDate.diff(firstDate, 'days') / 365;
    const annualizedReturn = Math.pow(1 + finalReturn, 1 / Math.max(years, 0.5)) - 1;
    
    // 最大回撤
    let maxDrawdown = 0;
    let peak = cumulativeReturns[0].cumulative_return;
    
    for (let i = 1; i < cumulativeReturns.length; i++) {
      const current = cumulativeReturns[i].cumulative_return;
      peak = Math.max(peak, current);
      const drawdown = (peak - current) / peak;
      maxDrawdown = Math.max(maxDrawdown, drawdown);
    }
    
    // 计算日收益率
    const dailyReturns = [];
    for (let i = 1; i < cumulativeReturns.length; i++) {
      const prevValue = cumulativeReturns[i-1].cumulative_return;
      const currentValue = cumulativeReturns[i].cumulative_return;
      dailyReturns.push((currentValue / prevValue) - 1);
    }
    
    // 波动率 (年化标准差)
    const mean = dailyReturns.reduce((sum, value) => sum + value, 0) / dailyReturns.length;
    const variance = dailyReturns.reduce((sum, value) => sum + Math.pow(value - mean, 2), 0) / dailyReturns.length;
    const dailyVolatility = Math.sqrt(variance);
    const volatility = dailyVolatility * Math.sqrt(252); // 年化
    
    // 夏普比率 (假设无风险利率为3%)
    const riskFreeRate = 0.03;
    const sharpeRatio = (annualizedReturn - riskFreeRate) / volatility;
    
    // 胜率
    const positiveReturns = dailyReturns.filter(r => r > 0).length;
    const winRate = positiveReturns / dailyReturns.length;
    
    return {
      finalReturn,
      annualizedReturn,
      maxDrawdown,
      volatility,
      sharpeRatio,
      winRate
    };
  };

  // 打开添加到策略组合的模态框
  const openAddToCombinationModal = () => {
    if (!results) {
      message.warning('请先运行回测后再添加到策略组合');
      return;
    }
    setShowCombinationModal(true);
    setSelectedCombination(null);
    setCombinationName('');
    setCreateNewCombination(false);
  };

  // 处理添加到策略组合
  const handleAddToCombination = async () => {
    try {
      if (!results) {
        message.warning('请先运行回测后再添加到策略组合');
        return;
      }

      const formValues = form.getFieldsValue();
      
      // 处理参数，确保类型正确
      const processedParams = {
        ischeckhs300: Boolean(formValues.ischeckhs300),
        hs300_limit: Number(formValues.hs300_limit),
        backCycle: String(formValues.backCycle),
        codes: selectedCodes,
        increaseday_range: Number(formValues.increaseday_range),
        highday_range: Number(formValues.highday_range),
        lowday_range: Number(formValues.lowday_range),
        sortType: Number(formValues.sortType),
        tradeType: Number(formValues.tradeType),
        isReal: false // 默认使用历史数据
      };
      
      // 处理开始日期
      if (formValues.startDate) {
        processedParams.startDate = moment(formValues.startDate).format('YYYY-MM-DD HH:mm:ss');
      }
      
      const strategyName = `${formValues.tradeType === 1 ? '双均线' : 
                           formValues.tradeType === 2 ? '收盘价高于均线' : 
                           formValues.tradeType === 3 ? '收盘价高于历史高点' : 
                           '高低点'} 策略`;
      
      const strategyData = {
        name: strategyName,
        parameters: processedParams,
        // 添加回测结果的摘要信息
        summary: {
          finalReturn: calculateStatistics(results.cumulative_returns).finalReturn,
          lastTradeDate: results.cumulative_returns[results.cumulative_returns.length - 1]?.date
        }
      };

      if (createNewCombination) {
        // 创建新组合
        if (!combinationName.trim()) {
          message.error('请输入组合名称');
          return;
        }

        await strategyCombinationApi.addCombination({
          name: combinationName,
          strategies: [strategyData]
        });
        message.success(`已创建新组合 "${combinationName}" 并添加当前策略`);
      } else if (selectedCombination !== null) {
        // 添加到现有组合
        const combination = strategyCombinations[selectedCombination];
        const updatedCombination = {
          ...combination,
          strategies: [...(combination.strategies || []), strategyData]
        };

        await strategyCombinationApi.updateCombination(
          selectedCombination,
          updatedCombination
        );
        message.success(`已将策略添加到组合 "${combination.name}"`);
      } else {
        message.error('请选择一个组合或创建新组合');
        return;
      }

      setShowCombinationModal(false);
      fetchStrategyCombinations();
    } catch (error) {
      console.error('添加策略到组合失败:', error);
      message.error('添加策略到组合失败');
    }
  };

  return (
    <div className="strategy-page">
      <Row gutter={[24, 24]}>
        <Col xs={24} lg={10}>
          <Card title="策略参数设置" bordered={false}>
            <Form
              form={form}
              layout="vertical"
              onFinish={handleSubmit}
              initialValues={{
                ischeckhs300: false,
                hs300_limit: 30,
                backCycle: "day",
                increaseday_range: 21,
                highday_range: 25,
                lowday_range: 17,
                sortType: 1,
                tradeType: 1
              }}
            >
              <Form.Item
                label="考虑沪深300"
                name="ischeckhs300"
                valuePropName="checked"
              >
                <Switch />
              </Form.Item>

              <Form.Item
                label="沪深300限制天数"
                name="hs300_limit"
                dependencies={['ischeckhs300']}
                rules={[{ required: true, message: '请输入沪深300限制天数' }]}
              >
                <InputNumber 
                  min={1} 
                  disabled={!form.getFieldValue('ischeckhs300')} 
                  style={{ width: '100%' }}
                />
              </Form.Item>

              <Form.Item
                label="回测周期"
                name="backCycle"
                rules={[{ required: true, message: '请选择回测周期' }]}
              >
                <Select>
                  {backCycleOpts.map(option => (
                    <Option key={option.value} value={option.value}>
                      {option.label}
                    </Option>
                  ))}
                </Select>
              </Form.Item>

              <Form.Item
                label="回测开始日期"
                name="startDate"
                tooltip="选择回测的开始日期，不选则使用全部可用数据"
              >
                <DatePicker 
                  style={{ width: '100%' }} 
                  format="YYYY-MM-DD"
                  placeholder="选择开始日期（可选）"
                  // onChange={(date, dateString) => {
                  //   // 如果选择了日期，设置为当天的开始时间
                  //   console.log('dateString :>> ', dateString);
                  //   console.log('date :>> ', date);
                  //   if (dateString) {
                  //     form.setFieldsValue({ startDate: `${dateString} 00:00:00` });
                  //   } else {
                  //     form.setFieldsValue({ startDate: null });
                  //   }
                  // }}
                />
              </Form.Item>

              <Form.Item
                label={
                  <div style={{ display: 'flex', justifyContent: 'space-between', width: '100%' }}>
                    <span>股票代码</span>
                    <Space>
                      &emsp;
                      <Tooltip title="保存当前组合">
                        <Button 
                          type="primary" 
                          icon={<SaveOutlined />} 
                          size="small"
                          onClick={openSaveGroupModal}
                        >保存为组合</Button>
                      </Tooltip>
                      <Tooltip title="加载组合">
                        <Button 
                          type="primary" 
                          icon={<FolderOpenOutlined />} 
                          size="small"
                          onClick={openLoadGroupModal}
                        >加载组合</Button>
                      </Tooltip>
                    </Space>
                  </div>
                }
                name="codes"
                rules={[{ required: true, message: '请选择至少一个股票代码' }]}
              >
                <div className="stock-code-selector">
                  <div className="selected-codes">
                    {selectedCodes.map(code => (
                      <Tag 
                        key={code} 
                        closable 
                        onClose={() => handleRemoveCode(code)}
                      >
                        {renderStockCodeWithName(code)}
                      </Tag>
                    ))}
                  </div>
                  <Button 
                    type="dashed" 
                    onClick={toggleStockSelector} 
                    style={{ width: '100%', marginTop: 8 }}
                  >
                    {showStockSelector ? '隐藏股票选择器' : '选择股票'}
                  </Button>
                  
                  {showStockSelector && (
                    <Collapse ghost>
                      <Panel header="历史数据" key="1">
                        <div className="stock-list">
                          {availableCodes.history.slice(0, 100).map(code => (
                            <Button
                              key={code}
                              size="small"
                              type={selectedCodes.includes(code) ? 'primary' : 'default'}
                              onClick={() => handleAddCode(code)}
                              style={{ margin: '4px' }}
                              title={stockNameMap[code] || ''}
                            >
                              {stockNameMap[code] ? `${code} (${stockNameMap[code]})` : code}
                            </Button>
                          ))}
                          {availableCodes.history.length > 100 && (
                            <Text type="secondary">还有 {availableCodes.history.length - 100} 个股票...</Text>
                          )}
                        </div>
                      </Panel>
                      {availableCodes.real.length > 0 && (
                        <Panel header="实盘数据" key="2">
                          <div className="stock-list">
                            {availableCodes.real.slice(0, 100).map(code => (
                              <Button
                                key={code}
                                size="small"
                                type={selectedCodes.includes(code) ? 'primary' : 'default'}
                                onClick={() => handleAddCode(code)}
                                style={{ margin: '4px' }}
                                title={stockNameMap[code] || ''}
                              >
                                {stockNameMap[code] ? `${code} (${stockNameMap[code]})` : code}
                              </Button>
                            ))}
                            {availableCodes.real.length > 100 && (
                              <Text type="secondary">还有 {availableCodes.real.length - 100} 个股票...</Text>
                            )}
                          </div>
                        </Panel>
                      )}
                    </Collapse>
                  )}
                </div>
              </Form.Item>

              <Form.Item
                label="涨幅天数范围"
                name="increaseday_range"
                rules={[{ required: true, message: '请输入涨幅天数范围' }]}
              >
                <InputNumber min={1} style={{ width: '100%' }} />
              </Form.Item>

              <Form.Item
                label="高点天数范围"
                name="highday_range"
                rules={[{ required: true, message: '请输入高点天数范围' }]}
              >
                <InputNumber min={1} style={{ width: '100%' }} />
              </Form.Item>

              <Form.Item
                label="低点天数范围"
                name="lowday_range"
                rules={[{ required: true, message: '请输入低点天数范围' }]}
              >
                <InputNumber min={1} style={{ width: '100%' }} />
              </Form.Item>

              <Form.Item
                label="排序类型"
                name="sortType"
                rules={[{ required: true, message: '请选择排序类型' }]}
              >
                <Select>
                  {sortTypeOpts.map(option => (
                    <Option key={option.value} value={option.value}>
                      {option.label}
                    </Option>
                  ))}
                </Select>
              </Form.Item>

              <Form.Item
                label="交易策略"
                name="tradeType"
                rules={[{ required: true, message: '请选择交易策略' }]}
              >
                <Select>
                  {tradeTypeOpts.map(option => (
                    <Option key={option.value} value={option.value}>
                      {option.label}
                    </Option>
                  ))}
                </Select>
              </Form.Item>

              <Form.Item>
                <Button 
                  type="primary" 
                  htmlType="submit" 
                  loading={loading}
                  icon={<LineChartOutlined />}
                  block
                >
                  开始回测
                </Button>
              </Form.Item>
            </Form>
          </Card>
        </Col>
        
        <Col xs={24} lg={14}>
          {results ? (
            <Card 
              title="回测结果" 
              bordered={false}
              className="results-card"
              extra={
                <Space>
                  <Button 
                    type="primary" 
                    icon={<TeamOutlined />} 
                    onClick={openAddToCombinationModal}
                  >
                    添加到组合
                  </Button>
                  <Button 
                    icon={<SaveOutlined />} 
                    onClick={openSaveGroupModal}
                  >
                    保存股票组合
                  </Button>
                </Space>
              }
            >
              <Tabs defaultActiveKey="summary">
                <TabPane tab="总览" key="summary">
                  <div className="results-section">
                    <Title level={4}>累计收益</Title>
                    <Row gutter={[16, 16]}>
                      {results.cumulative_returns && results.cumulative_returns.length > 0 && (() => {
                        const stats = calculateStatistics(results.cumulative_returns);
                        return (
                          <>
                            <Col xs={24} sm={12} md={8}>
                              <Card>
                                <Statistic
                                  title="最终收益率"
                                  value={(stats.finalReturn * 100).toFixed(2)}
                                  precision={2}
                                  valueStyle={{ color: stats.finalReturn >= 0 ? '#3f8600' : '#cf1322' }}
                                  suffix="%"
                                />
                              </Card>
                            </Col>
                            <Col xs={24} sm={12} md={8}>
                              <Card>
                                <Statistic
                                  title="年化收益率"
                                  value={(stats.annualizedReturn * 100).toFixed(2)}
                                  precision={2}
                                  valueStyle={{ color: stats.annualizedReturn >= 0 ? '#3f8600' : '#cf1322' }}
                                  suffix="%"
                                />
                              </Card>
                            </Col>
                            <Col xs={24} sm={12} md={8}>
                              <Card>
                                <Statistic
                                  title="最大回撤"
                                  value={(stats.maxDrawdown * 100).toFixed(2)}
                                  precision={2}
                                  valueStyle={{ color: '#cf1322' }}
                                  suffix="%"
                                />
                              </Card>
                            </Col>
                            <Col xs={24} sm={12} md={8}>
                              <Card>
                                <Statistic
                                  title="年化波动率"
                                  value={(stats.volatility * 100).toFixed(2)}
                                  precision={2}
                                  valueStyle={{ color: '#1890ff' }}
                                  suffix="%"
                                />
                              </Card>
                            </Col>
                            <Col xs={24} sm={12} md={8}>
                              <Card>
                                <Statistic
                                  title="夏普比率"
                                  value={stats.sharpeRatio.toFixed(2)}
                                  precision={2}
                                  valueStyle={{ color: stats.sharpeRatio >= 1 ? '#3f8600' : (stats.sharpeRatio >= 0 ? '#faad14' : '#cf1322') }}
                                />
                              </Card>
                            </Col>
                            <Col xs={24} sm={12} md={8}>
                              <Card>
                                <Statistic
                                  title="胜率"
                                  value={(stats.winRate * 100).toFixed(2)}
                                  precision={2}
                                  valueStyle={{ color: '#1890ff' }}
                                  suffix="%"
                                />
                              </Card>
                            </Col>
                          </>
                        );
                      })()}
                    </Row>
                    
                    <div className="chart-container" style={{ marginTop: '20px', height: '400px' }}>
                      {renderReturnsChart(results.cumulative_returns)}
                    </div>
                    
                    <Divider />
                    
                    <Title level={4}>交易记录</Title>
                    <Table
                      columns={columns}
                      dataSource={results.trade_log?.slice().reverse().map((item, index) => ({ ...item, key: index }))}
                      size="middle"
                      pagination={{ pageSize: 10 }}
                      scroll={{ x: 'max-content' }}
                    />
                  </div>
                </TabPane>
                
                <TabPane tab="回撤分析" key="drawdowns">
                  <div className="results-section">
                    <Title level={4}>
                      <Space>
                        <ArrowDownOutlined style={{ color: '#cf1322' }} />
                        前5大回撤
                      </Space>
                    </Title>
                    
                    {results.top_drawdowns && results.top_drawdowns.length > 0 ? (
                      <Table
                        dataSource={results.top_drawdowns.map((item, index) => ({ 
                          ...item, 
                          key: index,
                          start_date: moment(item.start_date).format('YYYY-MM-DD'),
                          end_date: moment(item.end_date).format('YYYY-MM-DD'),
                          depth_percent: formatDrawdownPercent(item.depth)
                        }))}
                        columns={[
                          {
                            title: '排名',
                            dataIndex: 'key',
                            key: 'rank',
                            render: (key) => <Badge count={key + 1} style={{ backgroundColor: '#cf1322' }} />
                          },
                          {
                            title: '开始日期',
                            dataIndex: 'start_date',
                            key: 'start_date',
                          },
                          {
                            title: '结束日期',
                            dataIndex: 'end_date',
                            key: 'end_date',
                          },
                          {
                            title: '最大回撤',
                            dataIndex: 'depth_percent',
                            key: 'depth',
                            render: (text) => <span style={{ color: '#cf1322' }}>{text}</span>
                          },
                          {
                            title: '持续天数',
                            dataIndex: 'duration',
                            key: 'duration',
                            render: (days) => `${days}天`
                          }
                        ]}
                        pagination={false}
                        size="middle"
                      />
                    ) : (
                      <Empty description="无回撤数据" />
                    )}
                  </div>
                </TabPane>
                
                <TabPane tab="月度收益" key="monthly">
                  <div className="results-section">
                    <Title level={4}>年度收益率</Title>
                    {results.yearly_returns && results.yearly_returns.length > 0 ? (
                      renderYearlyReturnsTable(results.yearly_returns)
                    ) : (
                      <Empty description="无年度收益数据" />
                    )}
                    
                    <Divider />
                    
                    <Title level={4}>月度收益热图</Title>
                    {results.monthly_returns && results.monthly_returns.length > 0 ? (
                      renderMonthlyReturnsHeatmap(results.monthly_returns)
                    ) : (
                      <Empty description="无月度收益数据" />
                    )}
                  </div>
                </TabPane>
              </Tabs>
            </Card>
          ) : (
            <Card bordered={false} className="placeholder-card">
              <div className="results-placeholder">
                <LineChartOutlined style={{ fontSize: 64, color: '#ccc' }} />
                <Text type="secondary">点击"开始回测"查看结果</Text>
              </div>
            </Card>
          )}
        </Col>
      </Row>

      {/* 股票组合管理模态框 */}
      <Modal
        title={groupModalMode === 'save' ? '保存股票组合' : '加载股票组合'}
        open={showGroupModal}
        onCancel={() => setShowGroupModal(false)}
        maskClosable={true}
        footer={null}
      >
        {groupModalMode === 'save' ? (
          <div>
            <Form layout="vertical">
              <Form.Item 
                label="组合名称" 
                required
                rules={[{ required: true, message: '请输入组合名称' }]}
              >
                <Input 
                  placeholder="请输入组合名称" 
                  value={groupName} 
                  onChange={(e) => setGroupName(e.target.value)} 
                />
              </Form.Item>
              <Form.Item label="包含股票">
                <div className="selected-codes-preview">
                  {selectedCodes.map(code => (
                    <Tag key={code}>{renderStockCodeWithName(code)}</Tag>
                  ))}
                </div>
              </Form.Item>
              <div style={{ textAlign: 'right' }}>
                <Space>
                  <Button onClick={() => setShowGroupModal(false)}>取消</Button>
                  <Button type="primary" onClick={saveCurrentGroup}>
                    {editingGroupId !== null ? '更新' : '保存'}
                  </Button>
                </Space>
              </div>
            </Form>
          </div>
        ) : (
          <div>
            {groupsLoading ? (
              <div style={{ textAlign: 'center', padding: '20px 0' }}>
                <Text type="secondary">加载中...</Text>
              </div>
            ) : stockGroups.length > 0 ? (
              <List
                itemLayout="horizontal"
                dataSource={stockGroups}
                renderItem={(item, index) => (
                  <List.Item
                    actions={[
                      <Button 
                        type="text" 
                        icon={<EditOutlined />} 
                        onClick={() => editGroup(item, index)} 
                      />,
                      <Popconfirm
                        title="确定要删除这个组合吗?"
                        onConfirm={() => deleteGroup(index)}
                        okText="确定"
                        cancelText="取消"
                      >
                        <Button type="text" danger icon={<DeleteOutlined />} />
                      </Popconfirm>
                    ]}
                  >
                    <List.Item.Meta
                      title={<a onClick={() => loadGroup(item)}>{item.name}</a>}
                      description={
                        <div className="group-codes-preview">
                          {item.codes.slice(0, 5).map(code => (
                            <Tag key={code} size="small">{renderStockCodeWithName(code)}</Tag>
                          ))}
                          {item.codes.length > 5 && <Tag>+{item.codes.length - 5}</Tag>}
                        </div>
                      }
                    />
                  </List.Item>
                )}
              />
            ) : (
              <div style={{ textAlign: 'center', padding: '20px 0' }}>
                <Text type="secondary">暂无保存的组合</Text>
              </div>
            )}
          </div>
        )}
      </Modal>

      {/* 策略组合模态框 */}
      <Modal
        title="添加到策略组合"
        open={showCombinationModal}
        onCancel={() => setShowCombinationModal(false)}
        onOk={handleAddToCombination}
        maskClosable={true}
        okText="确定"
        cancelText="取消"
      >
        <div style={{ marginBottom: 16 }}>
          <Switch
            checked={createNewCombination}
            onChange={setCreateNewCombination}
            style={{ marginRight: 8 }}
          />
          创建新组合
        </div>

        {createNewCombination ? (
          <Form layout="vertical">
            <Form.Item 
              label="组合名称" 
              required
              rules={[{ required: true, message: '请输入组合名称' }]}
            >
              <Input 
                placeholder="请输入组合名称" 
                value={combinationName} 
                onChange={(e) => setCombinationName(e.target.value)} 
              />
            </Form.Item>
          </Form>
        ) : (
          <div>
            {combinationsLoading ? (
              <div style={{ textAlign: 'center', padding: '20px 0' }}>
                <Text type="secondary">加载中...</Text>
              </div>
            ) : strategyCombinations.length > 0 ? (
              <List
                itemLayout="horizontal"
                dataSource={strategyCombinations}
                renderItem={(item, index) => (
                  <List.Item
                    onClick={() => setSelectedCombination(index)}
                    className={selectedCombination === index ? 'selected-item' : ''}
                    style={{ 
                      cursor: 'pointer', 
                      padding: '8px 16px',
                      backgroundColor: selectedCombination === index ? '#e6f7ff' : 'transparent'
                    }}
                  >
                    <List.Item.Meta
                      title={item.name}
                      description={`包含 ${item.strategies?.length || 0} 个策略`}
                    />
                  </List.Item>
                )}
              />
            ) : (
              <Empty description="暂无策略组合，请先创建" />
            )}
          </div>
        )}
      </Modal>
    </div>
  );
};

export default Strategy; 